package middleware.llvm.instruction;

import middleware.llvm.enums.BinaryOpType;
import middleware.llvm.value.Value;

import java.io.PrintStream;

/**
 * 二元运算指令，如加法、减法
 *
 * @author 杨凯伟
 * @date 2024/10/30
 */
public class BinaryInstruction extends Instruction {
    private final BinaryOpType op;
    private Value left;
    private Value right;

    public BinaryInstruction(BinaryOpType op, Value left, Value right) {
        super(left.getType(), left, right);
//        assert left.getType().equals(right.getType());
        this.op = op;
        this.left = left;
        this.right = right;
    }

    public BinaryOpType getOp() {
        return op;
    }


    public Value getLeft() {
        return left;
    }

    public Value getRight() {
        return right;
    }

    public void setLeft(Value left) {
        this.left = left;
    }

    public void setRight(Value right) {
        this.right = right;
    }

    @Override
    public void replaceOperand(int pos, Value newOperand) {
        super.replaceOperand(pos, newOperand);
        switch (pos) {
            case 0 -> left = newOperand;
            case 1 -> right = newOperand;
        }
    }

    @Override
    public void dump(PrintStream out) {
        out.printf("  %s = %s %s %s, %s\n", getName(), op.name().toLowerCase(), getType().toString(), left.getName(), right.getName());
    }
}
